package com.spyx.receiver;

import com.rabbitmq.client.Channel;
import com.spyx.common.constant.MqConst;
import com.spyx.service.ProductSearchService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//接收mq的消息
@Component
public class SkuReceiver {
    @Autowired
    private ProductSearchService productSearchService;

    //创建方法，监听消息的发送-用来监听商品上架的消息
    //@Queue 指定队列信息
    // @Exchange 指定交换机信息
    // key 指定路由键的信息
    //durable  标记是否持久化
    @RabbitListener(
            bindings = @QueueBinding(value =@Queue(value = MqConst.QUEUE_GOODS_UPPER,durable = "true"),
                                    exchange = @Exchange(value = MqConst.EXCHANGE_GOODS_DIRECT),
                                    key = {MqConst.ROUTING_GOODS_UPPER})
    )
    public void upper(Long skuId, Message message, Channel channel) throws  Exception{
        System.out.println("接收消息-up-"+skuId);
        //1.获取消息中的skuId
        if(skuId!=null){
            //发送给es
            productSearchService.uppersku(skuId);
        }
        //2.消息手动确认
        /**
         * 第一个参数：表示收到的消息的标号
         * 第二个参数：如果为true表示可以签收多个消息
         */
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    //创建方法，监听消息的发送-用来监听商品下架的消息
    @RabbitListener(
            bindings = @QueueBinding(value =@Queue(value = MqConst.QUEUE_GOODS_LOWER,durable = "true"),
                    exchange = @Exchange(value = MqConst.EXCHANGE_GOODS_DIRECT),
                    key = {MqConst.ROUTING_GOODS_LOWER})
    )
    public void down(Long skuId, Message message, Channel channel) throws  Exception{
        System.out.println("接收消息-down-"+skuId);
        //1.获取消息中的skuId
        if(skuId!=null){
            //发送给es
            productSearchService.downsku(skuId);
        }
        //2.消息手动确认
        /**
         * 第一个参数：表示收到的消息的标号
         * 第二个参数：如果为true表示可以签收多个消息
         */
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
